<template>
  <div ref="componentWrap" class="component-wrap">
    <div v-if="groupLen" class="tip">请添加图片素材</div>
    <div v-else>
      <canvas ref="picSliderCanvas" />
    </div>
    <ShowBorder v-if="borderShow" :border-attrs="borderAttrs" />
  </div>
</template>

<script>
import { CanvasSlider } from '@/utils/animation'
import { mapState } from 'vuex'
import ShowBorder from '@/components/Editor/ShowBorder.vue'
import { debounce, pick } from 'lodash'
import { borderAttr } from '@/custom-component/component-list'

export default {
  name: 'Picture',
  components: { ShowBorder },
  props: {
    element: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      width: 0,
      height: 0,
    }
  },
  computed: {
    ...mapState(['curComponent']),
    groupLen() {
      return !this.element.srcGroup.length
    },
    borderAttrs() {
      const attrs = Object.keys(borderAttr)
      console.log('borderAttrs', this.element.borderSW, pick(this.element, [...attrs, 'width', 'height', 'id']))
      return pick(this.element, [...attrs, 'width', 'height', 'id'])
    },
    borderShow() {
      return Number(this.element?.borderSW) === 1
    },
  },
  watch: {
    element: {
      deep: true,
      handler(newVal) {
        const watchVal = JSON.stringify(
          pick(newVal, [
            'picScaleType',
            'picShowTime',
            'picStyleIn',
            'picStyleInTime',
            'picStyleOut',
            'picStyleOutTime',
            'playTimes',
            'srcGroup',
            'siderType',
            'width',
            'height',
            'rotation',
          ]),
        )
        if (watchVal !== this?.oldElVal) {
          this.restSlider()
        }
        this.oldElVal = watchVal
      },
    },
    groupLen(val) {
      if (!val && this.slider) {
        this.slider.dispose()
        this.slider = null
      }
    },
  },
  mounted() {
    this.restSlider = debounce(this.restSlider.bind(this), 300)
    this.drawImage()
  },
  beforeDestroy() {
    this.slider && this.slider.dispose()
  },
  methods: {
    drawImage() {
      this.$nextTick(() => {
        const { picSliderCanvas, componentWrap } = this.$refs
        if (!this?.slider && picSliderCanvas) {
          this.slider = new CanvasSlider({
            data: this.element,
            canvasEl: picSliderCanvas,
            componentWrapEl: componentWrap,
          })
          this.slider.init()
        }
      })
    },
    restSlider() {
      if (this.slider) {
        this.slider.restSlider({
          data: this.element,
        })
      } else {
        this.$nextTick(() => {
          this.drawImage()
        })
      }
    },
  },
}
</script>
<style lang="scss" scoped></style>
